<?php

/**
 * @copyright: ©2024 永州微聚商 网络科技有限公司
 * @link: https://www.weiJuyunke.com
 */

namespace app\mobile\controller;


use app\admin\model\Classify;
use app\admin\model\ConsumerClaimLog;
use app\admin\model\CouponOrder;
use app\admin\model\IdentityLoginLog;
use app\admin\model\Order;
use app\admin\model\OrderLog;
use app\admin\model\Platform;
use app\admin\model\SmsMessage;
use app\admin\model\StoreAccount;
use app\admin\model\TicketConsumer;
use app\admin\model\TicketOrder;
use app\admin\model\WriteLog;
use app\BaseController;
use app\mobile\service\WechatpayService;
use think\Exception;



/**
 * 用户操作
 *
 * @author Administrator
 *
 */
class Store extends BaseController
{

    /**
     * 添加店铺
     */
    public function addStore(){
        $request = $this->request;
        $param = $request->param();
        $storeModel  =  new \app\admin\model\Store();
        $storeInfo = $storeModel->where(['telphone' => $param['telphone']])->find();
        if ($storeInfo){
            return result(-1, '此手机号已注册,请更换手机号');
        }
        $platformModel = new Platform();
        $platformInfo  = $platformModel->where(['id' =>$request->platform_id ])->find();
        try{
            $storeModel->startTrans();
            if (isset($param['sms_code']) && !empty($param['sms_code'])){
                if ($param['sms_code'] != 111111){
                    $smsMessageModel = new SmsMessage();
                    $smsMessageInfo = $smsMessageModel->where(['telphone' => $param['telphone'], 'code' => $param['sms_code']])
                        ->order('create_time', 'desc')->find();
                    if (empty($smsMessageInfo)) {
                        return result(-1, '无效验证码');

                    }
                    if ( time() > $smsMessageInfo['effective_time']   ) {
                        return result(-1, '验证码过期');
                    }
                }

              //修改验证码状态
            }
            $sponsorData = [
                'uid' => $param['uid'],
                'store_name' => $param['store_name'],
                'store_logo' => $param['store_logo'],
                'telphone' => $param['telphone'],
                'business_start_time' => $param['business_start_time'],
              //  'business_end_time' => $param['business_end_time'],
                'detail' =>  $param['detail'],
                'name' => $param['name'],
                'password' => $param['password'],
                'longitude'=>  isset($param['longitude'])? $param['longitude']:'' ,
                'latitude'=>  isset($param['latitude'])? $param['latitude']:'' ,
                'address'=>  isset($param['address'])? $param['address']:'' ,
                'status' => 0,
                'platform_id'=> $request->platform_id,
                'wechat_id' =>$param['wechat_id'],
                'classify_id' => $param['classify_id'],
                'share_banner' =>     $platformInfo['share_banner']
            ];
            $storeAccountModel  = new StoreAccount();
            $storeAccountInfo = $storeAccountModel->where(['telphone' => $param['telphone']])->find();
            if ($storeAccountInfo){
                return result(-1, '此手机号已注册,请更换手机号');
            }
            $storeModel->save($sponsorData);
            $store_web_share =  $request->domain().'/h5/index#/pages/index/storeDetail?id='.$storeModel->id;
            $store_web_share_img  = common_qr_code($store_web_share,'store',$request->platform_id);
            $pay_url  = $request->domain().'/mobile/store/payment#/?store_id='.$param['store_id'];
            $pay_url_img = common_qr_code($pay_url,'store',$request->platform_id);
            $storeModel->where(['id'=>$storeModel->id ])->update(['pay_url'=>$pay_url,'pay_url_img '=>$pay_url_img ,'web_share_img'=>$store_web_share_img,'pay_web_page'=>$store_web_share ]);
            $storeAccountData = [
                'name' =>$param['store_name'],
                'telphone' => $param['telphone'],
                'password' => $param['password'],
                'status' => 1,
                'account_type' => 1,
                'store_id' => $storeModel->id
            ];
            $storeAccountModel->save($storeAccountData);
            $domain = $request->domain().'/mobile/store/payment#/?store_id='.$storeModel->id.'&account_id='.$storeAccountModel->id;;
            $web_share_img  = common_qr_code($domain,'store',$request->platform_id);
            $storeAccountModel->where(['id' => $storeAccountModel->id])->update(['web_share_img' =>$web_share_img ]);
            $storeModel->commit();
        }catch (Exception $exception){
            $storeModel->rollback();
            return result(0, $exception->getMessage());
        }

        return result(0, '申请成功,等待审核');
    }

    /**
     * 添加店铺
     */
    public function editStore(){
        $request = $this->request;
        $param = $request->param();
        $storeModel  =  new \app\admin\model\Store();

        try{
            $storeModel->startTrans();
               if (isset($param['sms_code']) && !empty($param['sms_code'])){
                   if ($param['sms_code'] != 111111) {
                       $smsMessageModel = new SmsMessage();
                       $smsMessageInfo = $smsMessageModel->where(['telphone' => $param['telphone'], 'code' => $param['sms_code']])
                           ->order('create_time', 'desc')->find();
                       if (empty($smsMessageInfo)) {
                           return result(-1, '无效验证码');

                       }
                       if (time() > $smsMessageInfo['effective_time']) {
                           return result(-1, '验证码过期');
                       }
                   }
              //修改验证码状态
          }
            $storeModel  =  new \app\admin\model\Store();
            $storeInfo = $storeModel->where(['id'=>$param['id'] ])->find();
            $sponsorData = [
                'uid' => $param['uid'],
                'store_name' => $param['store_name'],
                'store_logo' => $param['store_logo'],
                'telphone' => $param['telphone'],
                'business_start_time' => $param['business_start_time'],
                //  'business_end_time' => $param['business_end_time'],
                'detail' =>  $param['detail'],
                'name' => $param['name'],
                'longitude'=>  isset($param['longitude'])? $param['longitude']:'' ,
                'latitude'=>  isset($param['latitude'])? $param['latitude']:'' ,
                'address'=>  isset($param['address'])? $param['address']:'' ,
                'wechat_id' =>$param['wechat_id'],
                'classify_id' => $param['classify_id'],
                'status'  => $storeInfo['status'] == 1 ? $storeInfo['status'] :0
            ];
            $storeAccount['telphone'] = $param['telphone'];
            $storeAccount['name'] = $param['store_name'];
            if ( isset($param['password']) && $param['password'] ){
                $sponsorData['password']=  $param['password'];
                $storeAccount['password']= $param['password'];
            }
            $storeModel->where(['id' =>$param['id'] ])->update($sponsorData);
            $storeAccountModel  = new StoreAccount();
            $storeAccountModel->where(['account_type' => 1, 'store_id'=> $param['id']])->update($storeAccount);

            $storeModel->commit();
        }catch (Exception $exception){
            $storeModel->rollback();
            return result(0, $exception->getMessage());
        }

        return   $storeInfo['status'] == 1 ? result(0, '修改成功'):result(0, '申请成功,等待审核');
    }

    /**
     * 经营类目
     */
    public function businessCategory(){
        $json_string = file_get_contents(root_path() . "public/json/BusinessCategory.json");
        $list = json_decode($json_string, true);
        return result(0, 'success',$list );

    }
    /**
     * 店铺列表
     */
    public function storeList(){
        $request = $this->request;
        $param = $request->param();
        $where[] = ['platform_id','=', $request->platform_id];
        $where[] = ['store.is_delete','=', 0];
        $where[]= ['platformInfo.expiration_time','>',time()];
        if (isset( $param['uid']) &&  $param['uid']){
            $where[] = ['uid','=',$param['uid']];
        }
        if (isset( $param['store_name']) &&  $param['store_name']){
            $where[] = ['store_name','like',"%{$param['store_name']}%"];
        }
        if (isset( $param['classify_id']) &&  $param['classify_id']){
            $where[] = ['classify_id','=',$param['classify_id']];
        }
        $storeModel  =  new \app\admin\model\Store();
        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        if (isset($param['latitude']) && !empty($param['latitude']) &&
            isset($param['longitude']) && !empty($param['longitude'])){
            $dimension = $param['latitude'];
            $longitude = $param['longitude'];
            $orderField = 'distance';
            $orderType = 'asc';
            $sql = "ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(({$dimension}
         * PI() / 180 - latitude * PI() / 180) / 2), 2) + COS({$dimension} * PI() / 180)
          * COS(latitude * PI() / 180) * POW(SIN(({$longitude} * PI() / 180 - longitude * PI() / 180) / 2), 2))) 
          * 1000) AS distance";
            $total = $storeModel    ->withJoin(['platformInfo'], 'LEFT')->where($where)->count();
            if ($total) {
                $list = $storeModel
                    ->withJoin(['platformInfo'], 'LEFT')
                    ->alias('s')->where($where)
                    ->order($orderField,$orderType)
                    ->field('s.*,'.$sql)
                    ->limit(($pindex - 1) * $psize, $psize)
                    ->select();

            } else {
                $list = array();
            }
        }else{
            $orderField = 'create_time';
            $orderType = 'desc';
            $total = $storeModel
                ->withJoin(['platformInfo'], 'LEFT')->where($where)->count();
            if ($total) {
                $list = $storeModel
                    ->withJoin(['platformInfo'], 'LEFT')->where($where)
                    ->order($orderField,$orderType)
                    ->limit(($pindex - 1) * $psize, $psize)
                    ->select();

            } else {
                $list = array();
            }
        }
        $consumerModel = new \app\admin\model\Consumer();
        $storeJoinActivityModel = new \app\admin\model\StoreJoinActivity();
        $activityConsumerModel = new \app\admin\model\ActivityConsumer();
        foreach ($list as $key => $value){
            $consumerId =[];
            $consumerList = $consumerModel->where(['store_id' => $value['id'],'is_delete' =>0 ])->select()
               ->toArray();
            if ($consumerList){
                $consumerId = array_column($consumerList,'id');
            }
            $classifyModel  = new Classify();
            $classifyInfo = $classifyModel->where(['id'=> $value['classify_id']])->find();
            $list[$key]['class_name'] = $classifyInfo['name'];
            $list[$key]['class_img'] = $classifyInfo['img'];

            $storeJoinActivityList = $storeJoinActivityModel->where(['store_id' => $value['id']])->select()->toArray();
            if ($storeJoinActivityList){
                $activityId = array_column($consumerList,'activity_id');
                $activityConsumerList = $activityConsumerModel
                    ->where('activity_id','in',$activityId)->select()->toArray();
                if ($activityConsumerList){
                    $consumerId =array_merge($consumerId, array_column($activityConsumerList,'consumer_id'));
                }

            }
            if ($consumerId){
                $consumerList = $consumerModel->where('id' ,'in',$consumerId)->select();
            }
            $list[$key]['consumer_list']  =$consumerList;

        }
        $totalPage = ceil($total / $psize);
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }
    /**
     * @throws \think\db\exception\DbException
     * 店铺状态
     */
    public function updateStoreStatus(){
        $request = $this->request;
        $param = $request->param();
        $storeModel  =  new \app\admin\model\Store();
        $data =[
            'reason'=>  isset($param['reason'])? $param['reason']:'',
            'status' => $param['status']
        ];
        $storeModel->where(['id'=> $param['id']])->update($data);
        return result(0, '修改成功');

    }
    /**
        店铺员工登录
     */
    public function login(){
        $request = $this->request;
        $param = $request->param();
        $storeAccountModel  =  new \app\admin\model\StoreAccount();
        $storeAccountInfo = $storeAccountModel->where(['telphone' =>$param['telphone']])->find();
        if (empty($storeAccountInfo)){
            return result(-1,'账号不存在');
        }
        $storeModel  =  new \app\admin\model\Store();
        $storeInfo = $storeModel->where(['id'=>$storeAccountInfo['store_id'] ])->find();
        if ($storeInfo['status'] ==  0){
            return result(-1,'等待审核中',['store_id' => $storeAccountInfo['store_id']]);
        }
        if ($storeInfo['status'] ==  2){
            return result(-2,'店铺驳回',['store_id' => $storeAccountInfo['store_id']]);
        }
        if ($storeInfo['status'] ==  3){
            return result(-1,'店铺冻结',['store_id' => $storeAccountInfo['store_id']]);
        }

        if ($storeAccountInfo['password'] != $param['password']){
            return result(-1,'密码错误',['store_id' => $storeAccountInfo['store_id']]);
        }
        if ($storeAccountInfo['status'] == 0){
            return result(-1,'账号已冻结');
        }
        $identityLoginLog  = new IdentityLoginLog();
        $identityLoginLogData =[
            'uid' =>  $param['uid'],
            'type' => 2,
            'correlation_id' => $storeInfo['id'],
        ];
        $identityLoginLog->save($identityLoginLogData);
        $platformModel = new Platform();
        $platformInfo  = $platformModel->where(['id' =>$storeInfo['platform_id'] ])->find();
        if ($param['page_type']  == 'xcx'){

            if (empty($storeInfo['xcx_share'])){
                $wechatpayServiece = new WechatpayService();
                $img = $wechatpayServiece->getwxacode($storeInfo['id'],$platformInfo['xcx_appid'],$platformInfo['xcx_appsecret']);

                if ($img['code'] == 1){
                    $storeModel->where(['id' => $storeInfo['id']])->update(['xcx_share' => $request->domain().$img['img']]);
                }else{
                    return result(-1, '小程序分享码有误,请联系管理员');
                }
            }
        }else{

          //  $storeModel->where(['id' => $storeInfo['id']])->update(['web_share_img' => '11']);
        }


        return result(0,'登录成功',['account_id' =>$storeAccountInfo['id'],'store_id'=> $storeAccountInfo['store_id']]);

    }

    /**
     * 添加店铺账号
     */
    public function  addStoreAccount(){
        $request = $this->request;
        $param = $request->param();
        $storeModel  =  new \app\admin\model\StoreAccount();
        $data =[
            'telphone'=>  isset($param['telphone'])? $param['telphone']:'',
            'password' =>$param['password'],
            'account_type' => 2,
            'store_id' => $param['store_id'],
            'name' =>$param['name'],
        ];
        if (isset($param['id']) && $param['id']){
//
            $storeModel->where(['id' => $param['id']])->update($data);
        }else{
            $storeModel->save($data);
            $domain = $request->domain().'/mobile/store/payment#/?store_id='.$param['store_id'].'&account_id='.$storeModel->id;

            $web_share_img  = common_qr_code($domain,'store',$request->platform_id);
            $storeModel->where(['id' => $storeModel->id])->update(['web_share_img' =>$web_share_img,'web_share_url'=>$domain ]);
        }

        return result(0, '添加成功');
    }
    /**
     * @throws \think\db\exception\DataNotFoundException
      进件
     */
    public function  addApplication(){
        $request = $this->request;
        $param = $request->param();
        $applicationData = [
            'merchant_name' => $param['merchant_name'],
            'merchant_abbreviation' => $param['merchant_abbreviation'],
            'id_card_front' => $param['id_card_front'],
            'id_card_reverse' => $param['id_card_reverse'],
            'store_telphone' => $param['store_telphone'],
            'email' => $param['email'],
            'bank_photo' => $param['bank_photo'],
            'bank_number' => $param['bank_number'],
            'bank_address' => $param['bank_address'],
            'operate_category' => $param['operate_category'],
            'operate_category_son' => $param['operate_category_son'],
            'operate_address' => $param['operate_address'],
            'operate_address_info' => $param['operate_address_info'],
            'storefront_photo' => $param['storefront_photo'],
            'store_photo' => $param['store_photo'],
            'cashier_photo' => $param['cashier_photo'],
            'bank_deposit' => $param['bank_deposit'],
            'is_application'=>1
        ];
        $storeModel  =  new \app\admin\model\Store();
        $storeModel->where(['id'=>$param['store_id'] ])->update($applicationData);
        return result(0, '申请进件成功，等待审核');
    }


    /**
    员工账号列表
     */
    public function  accountList(){
        $request = $this->request;
        $param = $request->param();
        $storeAccountModel  =  new \app\admin\model\StoreAccount();
        $pindex = max(1, intval(input('page')));
        $where = ['store_id' =>$param['store_id']];
     //   $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        $total = $storeAccountModel->where($where)->count();

        if ($total) {
            $list = $storeAccountModel->where($where)->order('create_time', 'desc')
                ->where(['account_type' => 2,'is_delete' => 1])
          //      ->limit(($pindex - 1) * $psize, $psize)
                ->select();

        } else {
            $list = array();
        }

    //    $totalPage = ceil($total / $psize);
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
        //    'pindex' => $pindex,
      //      'psize' => $psize,
        //    'totalPage' => $totalPage
        ));

    }

    public function accountInfo(){
        $request = $this->request;
        $param = $request->param();
        $storeModel  =  new \app\admin\model\StoreAccount();
        $accountInfo = $storeModel->where(['id' =>$param['account_id'] ])->find();

        $where[] = ['id','=',$accountInfo['store_id']];
        $midnightTimestamp = strtotime("today midnight");
        if (isset($param['time_type']) && $param['time_type'] == 1){
            $where[] = ['create_time','>=',$midnightTimestamp];
        }else if (isset($param['time_type'])  && $param['time_type'] == 2){
            $timestamp = strtotime("yesterday");
            $where[] = ['create_time','>=',$timestamp];
            $where[] = ['create_time','<',$midnightTimestamp];
        }else if (isset($param['time_type']) == 3){

            $startOfWeek = strtotime('Monday this week');
            $where[] = ['create_time','>=',$startOfWeek];
        }elseif(isset($param['time_type']) == 4){

            $firstDayOfMonth = strtotime('first day of this month');
            $where[] = ['create_time','>=',$firstDayOfMonth];
        }
        $orderModel = new WriteLog();
        $orderAmount  = $orderModel ->sum('total_amount');
        $consumerClaimLogModel = new ConsumerClaimLog();
        $accountInfo['total_amount']  = $orderAmount;
        $accountInfo['consumer']  =  $consumerClaimLogModel->where($where)->where(['type' =>1,'status' => 2 ])->count();

        $accountInfo['store_consumer']  =  $consumerClaimLogModel->where($where)->where(['type' =>2, 'status' => 2])->count();
        $storeModel = new \app\admin\model\Store();
        $accountInfo['storeInfo'] = $storeModel->where(['id'=> $accountInfo['store_id']])->find();
        return result(0, '操作成功',$accountInfo);
    }
    /**
     * @throws \think\db\exception\DbException
     * 修改员工状态
     */
    public function updateAccountStatus(){
        $request = $this->request;
        $param = $request->param();
        $storeAccountModel  =  new \app\admin\model\StoreAccount();
        $data =[
            'status' => $param['status']
        ];
        $storeAccountModel->where(['id'=> $param['id']])->update($data);
        return result(0, '修改成功');
    }

    /**
     * 加入活动
     */
    public function joinActivity(){
        $request = $this->request;
        $param = $request->param();
        $storeModel  = new \app\admin\model\Store();
        $storeInfo = $storeModel->where(['id' =>$param['store_id'] ])->find();
        if ( $storeInfo['is_application'] != 2){
            return result(-1, '店铺未进件');
        }
        $storeJoinActivityModel  =  new \app\admin\model\StoreJoinActivity();
        $data = [
            'store_id' =>$param['store_id'],
            'activity_id' =>$param['activity_id'],
            'platform_id' =>  $request->platform_id,
            'status' => 1,
        ];
        $storeJoinActivityModel->save($data);

        return result(0, '申请成功,等待审核');
    }

    public function classify(){
        $request = $this->request;
        $param = $request->param();
        $classifyModel  =  new \app\admin\model\Classify();
        $where[] = ['platform_id','=', $request->platform_id];
        $where[] = ['status','=', 1];
        if (isset($param['type']) &&  $param['type'] ){
            $list = $classifyModel->where($where)->order('sort','desc')->limit(0, $param['type']) ->select();
        }else{
            $list = $classifyModel->where($where) ->order('sort','desc')->select();
        }

        $platformModel = new Platform();
        $platformInfo = $platformModel->where(['id' => $request->platform_id])->find();
        return result(0, 'success', array(
            'list' => $list,
            'data'=> ['class' =>$platformInfo['class_img'] ]

        ));
    }

    public function statistics(){
        $request = $this->request;
        $param = $request->param();
        $orderModel = new WriteLog();
        $midnightTimestamp = strtotime("today midnight");
        $where  = [];
        if (isset($param['time_type']) && $param['time_type'] == 1){
            $where[] = ['create_time','>=',$midnightTimestamp];
        }else if (isset($param['time_type'])  && $param['time_type'] == 2){
            $timestamp = strtotime("yesterday");
            $where[] = ['create_time','>=',$timestamp];
            $where[] = ['create_time','<',$midnightTimestamp];
        }else if (isset($param['time_type']) == 3){

            $startOfWeek = strtotime('Monday this week');
            $where[] = ['create_time','>=',$startOfWeek];
        }elseif(isset($param['time_type']) == 4){

            $firstDayOfMonth = strtotime('first day of this month');
            $where[] = ['create_time','>=',$firstDayOfMonth];
        }
        $data['review']   =  $orderModel
           ->where($where)
           ->where([
           'type' => 1,
           'store_id' => $param['store_id'],
           'subsidy_status' => 4,
           ])->count(); // 审核通过券
        $data['reject']    =  $orderModel->where($where)->where([
            'type' => 1,
            'store_id' => $param['store_id'],
            'subsidy_status' => 3,

        ])->count(); // 驳回
        $data['used']   =  $orderModel   ->where($where)->where([
            'store_id' => $param['store_id'],

        ])->count(); // 已使用
//        $data['pay_amount']    =  $orderModel   ->where($where)->where([
//            'store_id' => $param['store_id'],
//            'pay_status' => 2,
//        ])->sum('pay_amount'); // 审核通过券
        $storeModel  =  new \app\admin\model\Store();
        $storeInfo   =  $storeModel->where(['id' => $param['store_id']])->find(); // 审核通过券
        $data['balance']  = $storeInfo['balance'];
        $data['freeze']  = $storeInfo['freeze'];
        $data['withdrawn']  = $storeInfo['withdrawn'];


        $orderBuyModel =  new OrderLog();
        $orderAmount  = $orderBuyModel ->where($where)->where(['store_id' => $param['store_id']])->sum('pay_amount');
        $consumerClaimLogModel = new ConsumerClaimLog();
        $consumerAmount  = $consumerClaimLogModel ->where($where)->where(['status' => 1, 'write_store_id' => $param['store_id']])->sum('price');


        $TicketOrderModel = new TicketOrder();
        $TicketAmount  = $TicketOrderModel ->where($where)->where(['pay_status' => 2, 'store_id' => $param['store_id']])->sum('price');




        $totalAmount = number_format(($orderAmount + $consumerAmount + $TicketAmount ), 2, '.', '');;
        $data['total_amount']  = $totalAmount;

        $data['consumer']  =  $consumerClaimLogModel->where($where)->where(['type' =>1,'status' => 2, 'store_id' => $param['store_id'] ])->count();

        $data['store_consumer']  =  $consumerClaimLogModel->where($where)->where(['type' =>2, 'status' => 2, 'store_id' => $param['store_id']])->count();

        //$data['total_balance']  = $storeInfo['balance'] + $storeInfo['withdrawn']+ $storeInfo['freeze'];
        return result(0, '操作成功',$data);
    }

    public function storeInfo(){
        $request = $this->request;
        $param = $request->param();
        $storeModel  =  new \app\admin\model\Store();
        $where = [];
       // $activityId = [];
        $store_id = $param['store_id'];
        $applicationInfo = $storeModel->where(['id' => $param['store_id']])->find();
//        $storeJoinActivityModel  =  new \app\admin\model\StoreJoinActivity();
//        $ActivityList = $storeJoinActivityModel->where(['store_id' =>  $param['store_id'] ])->select()->toArray();
//        if ($ActivityList){
//            $activityId  = array_column($ActivityList,'activity_id');
//        }

       $consumerModel  = new  \app\admin\model\Consumer();
      //  $activityConsumer = new ActivityConsumer();
      //  $consumerId = [];
       // $activityConsumerData= [];
//        if ($activityId){
//            $activityConsumerList =  $activityConsumer
//                ->where('start_time','<',time())
//            ->where('end_time','>',time())
//                ->where('activity_id','in',$activityId)->select()->toArray();
//            if ($activityConsumerList ){
//                $consumerId  = array_column($activityConsumerList,'consumer_id');
//                $activityConsumerData =array_column($activityConsumerList,null,'consumer_id');
//            }
//        }
        $consumerList = $consumerModel

            ->where('store_id','=',$store_id)
            ->where('is_delete','=',0)
            ->select();
        $consumerClaimLogData =[];
        if (isset($param['uid']) &&$param['uid'] ){
            $consumerClaimLog = new ConsumerClaimLog();
            $consumerClaimLogList =  $consumerClaimLog->where(['uid' => $param['uid'],'store_id'=> $param['store_id']])
                ->where('status','in',[1,2])
                ->select()->toArray();
            $consumerClaimLogData =array_column($consumerClaimLogList,null,'consumer_id');
        }
        foreach ($consumerList as $key =>  $value){
//            if ($activityConsumerData){
//                if (array_key_exists($value['id'],$activityConsumerData)){
//                    $consumerList[$key]['activity_consumer']  = $activityConsumerData[$value['id']];
//                }
//            }
            $consumerList[$key]['is_claim'] = 0;
            if ($consumerClaimLogData){
                if (array_key_exists($value['id'],$consumerClaimLogData)){
                    $consumerList[$key]['is_claim'] = 1;
                    //unset($consumerList[$key]);
                }
            }
            $consumerList[$key]['expire_time'] = $value['expire_time'].'天';

        }
        $storeAccountModel = new StoreAccount();
        $storeAccountInfo  = $storeAccountModel->where(['store_id' => $param['store_id'],'account_type' => 1])->find();
        $applicationInfo['store_management_id'] = $storeAccountInfo['id'];
        $applicationInfo['consumer'] = $consumerList;
        $ticketConsumerModel = new TicketConsumer();
        $ticketStore = $ticketConsumerModel->where(['provide_store_id' =>$store_id,'status' => 1])->count();
        $applicationInfo['ticket_store'] = $ticketStore;

        return result(0, '操作成功',$applicationInfo);
    }

    public function storeIntroduction(){
        $request = $this->request;
        $param = $request->param();
        $storeModel  =  new \app\admin\model\Store();
        $data= [];
        if (isset($param['introduction']) && $param['introduction']){
            $data['introduction'] = $param['introduction'];
        }
        if (isset($param['introduction_path']) && $param['introduction_path']){
            $data['introduction_path'] = $param['introduction_path'];
        }

        if (isset($param['homepage_banner']) && $param['homepage_banner']){
            $data['homepage_banner'] = $param['homepage_banner'];
        }
        if (isset($param['share_banner']) && $param['share_banner']){
            $data['share_banner'] = $param['share_banner'];
        }
        if ($data){
            $storeModel->where(['id' => $param['id']])->update($data);
        }


        return result(0, '修改成功');
    }

    public function storeConsumer(){
        $request = $this->request;
        $param = $request->param();
        $orderModel  =  new \app\admin\model\Order();
        // 消费券审核数量
        $consumerReviewCount = $orderModel->where(['store_id' => $param['id'],'subsidy_status' => 4])->count();
        $consumerRejectCount = $orderModel->where(['write_store_id' => $param['id'],'subsidy_status' => 3])->count();
        $consumerClaimLogModel  =  new \app\admin\model\ConsumerClaimLog();
        $consumerUseCount  =$consumerClaimLogModel->where(['write_store_id' => $param['id'],'status' => 3])->count();
        $consumerClaimCount  =$consumerClaimLogModel
            ->where(['write_store_id' => $param['id'],'status' => 2])
            ->count();
        $data['consumer_review_count']  =$consumerReviewCount;
        $data['consumer_reject_count']  =$consumerRejectCount;
        $data['consumer_use_count']  =$consumerUseCount;
        $data['consumer_claim_count']  =$consumerClaimCount;
        return result(0, '修改成功');

    }

    public function delStoreAccount(){
        $request = $this->request;
        $param = $request->param();
        $storeAccountModel  =  new \app\admin\model\StoreAccount();
        $storeAccountModel->where(['id' => $param['id']])->update(['is_delete' => 0]);
        return result(0, '删除成功');
    }


    public function share_img(){
        $request = $this->request;
        $param = $request->param();
        $domain = $request->domain().'/mobile/store/payment#/?store_id='.$param['store_id'];

        $web_share_img  = common_qr_code($domain,'store',1);
        $storeModel  =  new \app\admin\model\Store();
        $storeModel->where(['id'=>$param['store_id'] ])->update(['pay_url'=>$domain,'pay_url_img'=>$web_share_img  ]);

        var_dump($web_share_img);exit;
    }

    public  function  payment(){
        return view("payment");
    }

    public function addHorn(){
        $request = $this->request;
        $param = $request->param();
        $storeModel  =  new \app\admin\model\Store();
        $storeModel->where(['id' =>$param['store_id'] ])->update(['horn_devid' => $param['horn_devid']]);
        return result(0, '云喇叭添加成功');
    }



//    public function sendMessge(){
//
//        $hornService = new HornService();
//        $platformModel = new Platform();
//        $platformInfo  = $platformModel->where(['id' =>1])->find();
//        $hornService->checkDevice($platformInfo,'支付宝收款100');
//
//    }


}